package com.yikome.uaa.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yikome.uaa.domain.Authority;
import com.yikome.uaa.domain.Role;
import com.yikome.uaa.domain.User;
import com.yikome.uaa.po.JwtUserPO;
import com.yikome.uaa.po.ResetMindPassword;
import com.yikome.uaa.po.UserLoginPO;
import com.yikome.uaa.service.AuthorityService;
import com.yikome.uaa.service.RoleService;
import com.yikome.uaa.service.UserService;
import com.google.common.base.Preconditions;
import com.itmuch.lightsecurity.annotation.PreAuthorize;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/uaa")
public class UaaManagerController {

	@Autowired
	private UserService userService ; 
	
	@Autowired
	private RoleService roleService ;
	
	@Autowired
	private AuthorityService authorityService ; 
	
	/**
	 * 登陆,需要用户名密码
	 * @param userRequest
	 * @return
	 */
	@PostMapping("/login")
	public JwtUserPO login(@RequestBody UserLoginPO userLoginPO) {
		
		Preconditions.checkArgument(StringUtils.isNotBlank(userLoginPO.getUsername()), "用户名不能为空....");
		Preconditions.checkArgument(StringUtils.isNotBlank(userLoginPO.getPassword()), "密码不能为空....");
		
		return userService.login(userLoginPO);
	}
	
	/**
	 * 分页查询用户,包含用户角色,可以通过用户名和角色进行过滤
	 */
	@GetMapping("/user/lists")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Page<User> findPageUsers(@PageableDefault(sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable,User userRequest) {
		return userService.findPageUsers(userRequest , pageable);
	}
	
	@GetMapping("/user/{userId}")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public User findUserDetails(@PathVariable("userId") Long userId) {
		return userService.findUserDetails(userId);
	}
	
	/**
	 * 新增用户,参数项包含用户名,密码,角色
	 */
	@PostMapping("/user")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public User saveUser(@RequestBody User userRequest) {
		Preconditions.checkArgument(StringUtils.isNotBlank(userRequest.getUsername()), "用户名不能为空....");
		Preconditions.checkArgument(StringUtils.isNotBlank(userRequest.getPassword()), "密码不能为空....");
		Preconditions.checkArgument(!userRequest.getRoles().isEmpty(), "角色不能为空....");
		
		int length = userRequest.getPassword().trim().length();
        Preconditions.checkArgument(length >= 6 && length <= 10, "密码长度为6-10位...");
		
		User user = userService.saveUser(userRequest);
		user.setPassword(null);
		user.setRoles(null);
		return user ; 
	}
	
	/**
	 * 修改用户,参数包含用户名,角色
	 */
	@PutMapping("/user")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Boolean updateUser(@RequestBody User userRequest) {
		Preconditions.checkArgument(userRequest.getId() != null, "用户ID不存在....");
		Preconditions.checkArgument(StringUtils.isNotBlank(userRequest.getUsername()), "用户名不能为空....");
		Preconditions.checkArgument(!userRequest.getRoles().isEmpty(), "角色不能为空....");
		//不能修改admin用户的
		User user = userService.find(userRequest.getId());
		Preconditions.checkArgument(user != null, "对应用户不存在...");
		Preconditions.checkArgument(!StringUtils.equalsIgnoreCase(user.getUsername(), "admin"), "最高用户不允许修改...");
		user = userService.updateUser(userRequest);
		user.setPassword(null);
		return true ; 
	}
	
	/**
	 * 重置用户密码
	 */
	@PutMapping("/user/crypto/reset/{userId}")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Boolean resetUserPassword(@PathVariable("userId") Long userId) {
		
		User user = userService.find(userId);
		Preconditions.checkArgument(user != null, "对应用户不存在...");
		Preconditions.checkArgument(!StringUtils.equalsIgnoreCase(user.getUsername(), "admin"), "最高用户不允许修改...");
		
		return userService.resetUserPassword(user);
	} 
	
	/**
	 * 修改自己的密码
	 */
	@PutMapping("/user/crypto/reset")
	@PreAuthorize("hasLogin()")
	public Boolean resetMindPassword(@RequestBody ResetMindPassword resetMindPasswordRequest) {
		
		Preconditions.checkArgument(StringUtils.isNotBlank(resetMindPasswordRequest.getOldPassword()),"原始密码不能为空...");
        Preconditions.checkArgument(StringUtils.isNotBlank(resetMindPasswordRequest.getNewPassword()),"新密码不能为空...");
        
        int length = resetMindPasswordRequest.getNewPassword().trim().length();
        Preconditions.checkArgument(length >= 6 && length <= 10, "密码长度为6-10位...");
        
        return userService.resetMindPassword(resetMindPasswordRequest);
	} 
	
	
	/**
	 * 删除用户
	 */
	@DeleteMapping("/user/{userId}")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Boolean deleteUser(@PathVariable("userId") Long userId) {
		
		User user = userService.find(userId);
		Preconditions.checkArgument(user != null, "对应用户不存在...");
		Preconditions.checkArgument(!StringUtils.equalsIgnoreCase(user.getUsername(), "admin"), "最高用户不允许修改...");
		return userService.deleteUser(user);
	}
	
	/**
	 * 获取所有角色查询(非分页,不含权限)
	 */
	@GetMapping("/role")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public List<Role> findRole(Role roleRequest){
		return roleService.findRole(roleRequest);
	}
	
	/**
	 * 获取一个角色明细,含权限
	 */
	@GetMapping("/role/{roleId}")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Role findRoleDetails(@PathVariable("roleId") Long roleId){
		return roleService.findRoleDetails(roleId);
	}
	
	/**
	 * 新增或保存一个角色(角色值,角色名称,权限)
	 */
	@PostMapping("/role")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Boolean saveUpdateRole(@RequestBody Role role) {
		
		Preconditions.checkArgument(StringUtils.isNotBlank(role.getValue()),"角色值不能为空...");
		return roleService.saveUpdateRole(role);
	}
	
	/**
	 * 删除一个角色
	 */
	@DeleteMapping("/role/{roleId}")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Boolean deleteRole(@PathVariable("roleId") Long roleId) {
		Role oldRole = roleService.find(roleId);
		Preconditions.checkArgument(oldRole != null, "角色不存在...");
		Preconditions.checkArgument(!StringUtils.equalsIgnoreCase(oldRole.getName(), "admin"), "最高权限不允许修改...");
		return roleService.deleteRole(oldRole);
	}
	
	/**
	 * 获取所有权限,(树状结构)
	 */
	@GetMapping("/authority")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public List<Authority> findAuthority(){
		return authorityService.findAllAuthority();
	}
	
	/**
	 * 新增或修改一个权限
	 */
	@PostMapping("/authority")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Authority saveUpdateAuthority(@RequestBody Authority authority) {
		Preconditions.checkArgument(StringUtils.isNotBlank(authority.getName()),"权限名不能为空...");
		Preconditions.checkArgument(authority.getParentId() != null,"上级菜单或目录不能为空...");
		Preconditions.checkArgument(authority.getType() != null,"类型不能为空...");
		Preconditions.checkArgument(authority.getOrderNum() != null,"排序不能为空...");
		return authorityService.saveUpdateAuthority(authority);
	}
	
	
	/**
	 * 删除一个权限
	 */
	@DeleteMapping("/authority/{authorityId}")
	@PreAuthorize("hasAnyRoles('admin','manager')")
	public Boolean deleteAuthority(@PathVariable("authorityId") Long authorityId) {
		
		return authorityService.deleteAuthority(authorityId);
	}
	
	
}
